package com.active.test.topic.producer;

import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @create 2019-11-26 下午12:56
 */
@Slf4j
public class JmsProduce_Topic_Persist {
    private static final String ACTIVEMQ_URL = "tcp://localhost:61616";
    private static final String TOPIC_NAME = "topic-atguigu";

    public static void main(String[] args) throws JMSException {
        //1.创建连接工厂，按照给定的url地址，采用默认用户名和密码
        final ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
        //2.通过连接工厂，获取连接的connection
        final Connection connection = activeMQConnectionFactory.createConnection();
        connection.start();

        //3.创建会话
        // 两个参数，第一个叫事务，第二个叫签收
        final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        //4.创建目的地（具体是队列还是主题）
        final Topic topic = session.createTopic(TOPIC_NAME);

        //5.创建消息的生产者
        final MessageProducer producer = session.createProducer(topic);
        //　显示声明使用持久化方式
        producer.setDeliveryMode(DeliveryMode.PERSISTENT);

        //6.通过使用消息生产者，生产3条消息发送到MQ的队列里
        for (int i = 0; i < 3; i++) {
            //7.创建消息
            // textMessage可以理解为一个字符串
            final TextMessage textMessage = session.createTextMessage("topic----" + i);
            //通过producer发送给MQ
            producer.send(textMessage);
        }

        //9关闭资源
        producer.close();
        session.close();
        connection.close();

        log.info("topic消息发布到mq完成");
    }
}
